package com.googlecode.triples.provider.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJBException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

public class EJBExceptionMapper implements ExceptionMapper<EJBException> {
	private static final Logger log = LoggerFactory.getLogger(EJBExceptionMapper.class);

	public Response toResponse(final EJBException e) {
		if (e.getCausedByException() instanceof WebApplicationException) {
			log.debug(e.toString(), e);
			final WebApplicationException webApplicationException = (WebApplicationException) e.getCausedByException();
			return webApplicationException.getResponse();
		} else if (e.getCausedByException() instanceof NoResultException) {
			log.debug(e.toString(), e);
			return Response.status(Response.Status.NOT_FOUND).build();
		} else if (e.getCausedByException() instanceof NonUniqueResultException) {
			log.debug(e.toString(), e);
			return Response.status(Response.Status.NOT_FOUND).build();
		}
		log.error(e.toString(), e);
		return Response.serverError().build();
	}
}
